﻿using FluorineFx.Json;
using HashidsNet;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace lxwmvc
{
    [weixin(typeof(WeiXin_UserInfo), weixincontroller.URL, weixincontroller.SCOPE)]
    public class defaultcontroller
    {
        public static bool TEST = false;

        public static void _init(pagebase pb)
        {
            pb["jsver"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.tostr(); 

            var jssdk = weixincontroller.GZH.JSSDK();
            pb["jssdk"] = jssdk;

            pb["fxtitle"] = "“广告加”分享文章新体验";
            pb["fximg"] = "http://" + weixincontroller.domain+"/AdImages/zituibao3.jpg";
            pb["fxurl"] = "http://" + weixincontroller.domain+"/hello";
        }

        /// <summary>
        /// 欢迎页面
        /// </summary>
        /// <param name="pb"></param>
        public static void hello(pagebase pb)
        {
            pb.cancelview();
            jshelper.redirect("http://mp.weixin.qq.com/s?__biz=MzI5NDA4OTk3Nw==&mid=400489295&idx=1&sn=f207a95b81f922f00dd112033d7d3bfa&scene=23&srcid=1104K6pXk7BBSrWI3KiPAgvA#rd");
        }


        /// <summary>
        /// 得到上传的图片信息
        /// </summary>
        /// <param name="pb"></param>
        public static void getuploadimg(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");

            var pi = queryhelper.pager(_tupian_.TABLE_NAME, "*", pb.orderbycolumn(_tupian_.tupianid, "desc"), pb.page, 10, " openid='" + openid.tosafe() + "' ");

            string ret = "ok";
            foreach (supermodel model in pi.data)
            {
                ret += "," + model[_tupian_.path];
            }

            if (pi.data.Count() < 10)
                ret += ",end";
            else
                ret += ",ok";

            pb.write(ret);
        }

        public static void getguanggao(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");


            var pi = queryhelper.pager("guanggao", "*", pb.orderbycolumn("guanggaoid", "desc"), pb.v_i("page1"), 10, " openid='" + openid.tosafe() + "' ");

            ArrayList arr = new ArrayList();
            foreach (supermodel model in pi.data)
            {
                arr.Add(new { 
                    text = model["text"],
                    img = model["img"],
                    link = model["guanggaoid"],
                });
            }
            pb.json(arr);
        }

        public static void loadguangaolink(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");

            var gg = queryhelper.get<_guanggao>("select text,link,img from guanggao where guanggaoid=@0",pb.v_i("id"));
            pb.json(gg);
        }

        public static void saveguanggaoxiugai(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");
            var model = pb.getmodel<_guanggao>();

            var ret = model.saveorupdate((o) => {
                o[_guanggao_.tianjiariqi] = DateTime.Now;
                o[_guanggao_.openid] = openid;
            }) ;

            pb.write(ret.identity+"");
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="pb"></param>
        public static void deleteuploadimg(pagebase pb)
        {
            var purl = pb.v_s("purl");
            queryhelper.execute("delete from tupian where path=@0", purl);
            pb.write("ok");
        }
        public static void deleteguanggao(pagebase pb)
        {
            var purl = pb.v_s("purl");
            queryhelper.execute("delete from guanggao where guanggaoid=@0", purl);
            pb.write("ok");
        }
        

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="pb"></param>
        public static void uploadimg(pagebase pb)
        {
            try
            {
                var img = pb.v_s("img");

                var filenamex = DateTime.Now.ToString("HHmmssfff") + WeiXin_Fun.CreateNonceStr(16);
                var filename = filenamex + ".jpg";
                var filenames = filenamex + "_200.jpg";
                try
                {
                    Directory.CreateDirectory(pb.Server.MapPath("/upload"));
                }
                catch { }

                var t = img.IndexOf("base64,");

                Image m = zfcontroller.GetImageFromBase64(img.Substring(t+7));

                var m2 = (Image)m.Clone();
                imagehelper.GetPicThumbnail(m,
                    Path.Combine(pb.Server.MapPath("/upload"), filename),
                    80);

                var small = imagehelper.cutsuoxiaimage(new Bitmap(m2), new int[2] { 200, 200 },true,true);
                small.Save(Path.Combine(pb.Server.MapPath("/upload"), filenames), ImageFormat.Jpeg);
                if (small!=null) small.Dispose();
                if (m2 != null) m2.Dispose();
                if (m != null) m.Dispose();
                var openid = cookieshelper.getcookie("openidx");
                var tupian = new _tupian();
                tupian.tianjiariqi = DateTime.Now;
                tupian.path = "/upload/" + filenames;
                tupian.openid = openid;

                tupian.saveorupdate();
                
                //保存文件
                //m.Save(Path.Combine(pb.Server.MapPath("/upload"), filename));

                pb.write("0|/upload/" + filenames);
                return;
            }
            catch { }
            pb.write("err");
        }

        public static void uploadguanggao(pagebase pb)
        {
            try
            {
                var img = pb.v_s("img");

                var filenamex = DateTime.Now.ToString("HHmmssfff") + WeiXin_Fun.CreateNonceStr(16);
                var filename = filenamex + ".jpg";
                //var filenames = filenamex + "_200.jpg";
                try
                {
                    Directory.CreateDirectory(pb.Server.MapPath("/upload"));
                }
                catch { }

                var t = img.IndexOf("base64,");

                Image m = zfcontroller.GetImageFromBase64(img.Substring(t + 7));


                m.Save(Path.Combine(pb.Server.MapPath("/upload"), filename), ImageFormat.Jpeg);
                
                if (m != null) m.Dispose();
                

                //保存文件
                //m.Save(Path.Combine(pb.Server.MapPath("/upload"), filename));

                pb.write("0|/upload/" + filename);
                return;
            }
            catch { }
            pb.write("err");
        }

        public static void ad(pagebase pb)
        {
            var r = pb.v_i("r");
            var link = queryhelper.get<string>("select link from ZTBAD where id=@0", r);

            pb.cancelview();
            pb.redirect(link);
        }

        static string regex = "<body[^>]+>([\\s.\\n\\r\\S]+)</body>";
        static System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                    | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        static System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
        public static void savebody(pagebase pb)
        {
            var html = pb.v_s("content");
            var code = pb.v_s("u");

            var index = html.IndexOf("<!-- .end. -->");
            html = html.Substring(0, index);

            var art = queryhelper.get<_Articles>("where code=@0", code);

            var body = "";
            using (StreamReader sr = new StreamReader(art.URL))
            {
                body = sr.ReadToEnd();
            }

            string result = reg.Replace(body, (m) =>
            {
                return m.Groups[0].Value.Replace(m.Groups[1].Value, html);
            });

            try
            {
                //复制一个新的
                File.Copy(art.URL, art.URL+"-"+DateTime.Now.ToString("yyyyMMddHHmmssfff")+".bak");
                File.Delete(art.URL);
            }
            catch { }
            using (StreamWriter sr = new StreamWriter(art.URL))
            {
                sr.Write(result);
            }

            pb.write("OK");
        }

        public static void index(pagebase pb)
        {

        }

        public static void set(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");

            if (TEST)
                openid = "o1bYhs0QWDnsTbqO6Sp65BXseTUI";

            var yonghu = queryhelper.get<_yonghu>("select * from yonghu where openid=@0", openid);
            var ads = queryhelper.query<_ZTBAD>("select top 3 * from ZTBAD where openid=@0 order by xuhao asc", openid);

            var style = yonghu.style;//0 是一条 1是两条 2是三条

            var adsnew = new _ZTBAD[3];
            for (int i = 0; i < adsnew.Count(); i++)
                adsnew[i] = new _ZTBAD()
                {
                    link = "",//链接到您的推广网址,例如：a.com或http://a.com等
                    url = "/AdImages/zituibao" + (i+1) + ".jpg?t="+DateTime.Now
                };

            for (int i = 0; i < ads.Count(); i++)
            {
                adsnew[i] = ads.ElementAt(i);
            }

            //if (style < 1) adsnew[1].link = "www.etuling.com/hello";
            //if (style < 2) adsnew[2].link = "www.etuling.com/hello";
            

            for (int i = 0; i < adsnew.Count(); i++)
            {
                if (adsnew[i].url == "")
                    adsnew[i].url = "/AdImages/zituibao" + (i + 1) + ".jpg?t=" + DateTime.Now;                    
            }

            pb["yonghu"] = yonghu;

            pb["ad0"] = adsnew[0];
            pb["ad1"] = adsnew[1];
            pb["ad2"] = adsnew[2];

            var code = pb.v_ss("code");
            if (code == "")
            {
                pb["code"] = queryhelper.get<string>("select top 1 code from Articles where openid=@0",openid);
            }
        }
        public static void setsave(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");           
            var adid = 3;
            var yonghu = queryhelper.get<_yonghu>("select * from yonghu where openid=@0", openid);
            //if (yonghu.style == 1) adid = 3;

            //另外两条需要受限制

            for (int i = 1; i <= adid; i++)
            {
                var t = pb.v_s("t"+i);
                var l = pb.v_s("l"+i);

                //if (l.isnull()) l = "www.etuling.com/hello";
                var ad = queryhelper.get<_ZTBAD>("select * from ZTBAD where openid=@0 and  xuhao=@1", openid, i);
                if (ad == null) ad = new _ZTBAD();
                ad.openid = openid;
                ad.url = t;
                ad.xuhao = i;
                ad.link = l;
                ad.saveorupdate();
            }


            pb.write("ok");
        }

        public static void upload(pagebase pb)
        {
            try
            {


                var img = pb.v_s("img");
                var t = img.IndexOf("base64,");

                Image photo = zfcontroller.GetImageFromBase64(img.Substring(t + 7));


                var filenamex = DateTime.Now.ToString("HHmmssfff") + WeiXin_Fun.CreateNonceStr(16);
                var x = filenamex + ".jpg";
                string fileNameB = "/AdImages/B-" + x + "";
                string fileName = "/AdImages/W-" + x + "";



                Bitmap map = new Bitmap(photo);
                map.Save(HttpContext.Current.Server.MapPath(fileNameB));

                Bitmap mapA = imagehelper.cutimage(map, new int[] { 640, 120 });

                mapA.Save(HttpContext.Current.Server.MapPath(fileName));
                if (mapA != null) mapA.Dispose();
                if (photo != null) photo.Dispose();
                if (map != null) map.Dispose();

                pb.write(fileName);
            }
            catch (Exception err)
            {
                dataloger.fatal("upload", err);
                pb.write(err.Message);
            }
        }


        /// <summary>
        /// 获取某一条广告的情况
        /// </summary>
        /// <param name="pb"></param>
        public static void r1(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");

            var code = pb.v_ss("u");

            string sql = @"select ReadCount,ClickCount,title,releasetime,code from Articles where code=@code
select count(1) from (select fromopenid,COUNT(1) as a from guanxi where fromopenid!=@openid and code=@code group by fromopenid) T
select wxfrom,COUNT(1) as c from guanxi where fromopenid=@openid and code=@code group by wxfrom
select top 10 * from (select city,COUNT(1) as a from guanxi where fromopenid=@openid and code=@code group by city) T order by T.a desc
select top 10 * from (select UserAgent,COUNT(1) as a from guanxi where fromopenid=@openid and code=@code group by UserAgent) T order by T.a desc";

            queryhelper.FUN((conn, tran) =>
            {
                using (var query = conn.QueryMultiple(sql, new { openid, code }))
                {
                    pb["model"] = query.ReadOne<supermodel>();

                    pb["fxcs"] = query.ReadOne<int>();


                    pb["fx1"] = query.Read<supermodel>().ToArray();
                    pb["fx2"] = query.Read<supermodel>().ToArray();
                    pb["fx3"] = query.Read<supermodel>().ToArray();
                };
                    
            });
        }

        public static void r(pagebase pb)
        {
            var openid = cookieshelper.getcookie("openidx");

            string sql = @"select COUNT(1) from Articles where openid=@open 
select isnull(SUM(ReadCount),0),isnull(SUM(ClickCount),0) from Articles where openid=@open
select count(1) from (select fromopenid,COUNT(1) as a from guanxi where fromopenid!=@open
and code in (select code from Articles where openid=@open ) group by fromopenid) T
select COUNT(1) from Articles where openid=@open and datediff(day,ReleaseTime,getdate())<7
select isnull(SUM(ReadCount),0),isnull(SUM(ClickCount),0) from Articles where openid=@open and datediff(day,ReleaseTime,getdate())<7
select count(1) from (select fromopenid,COUNT(1) as a from guanxi where fromopenid!=@open
and code in (select code from Articles where openid=@open and datediff(day,ReleaseTime,getdate())<7 ) group by fromopenid) T
select top 10 Title,ReleaseTime,ReadCount,ClickCount,code from Articles where openid=@open order by ReleaseTime desc";

            queryhelper.FUN((conn, tran) => {
                using (var query = conn.QueryMultiple(sql, new { open =openid}))
                {
                    pb["zfwz"] = query.ReadOne<int>();
                    var t1 = query.ReadOne<supermodel>();
                    pb["wzyd"] = t1.Value<int>(0); pb["ggdj"] = t1.Value<int>(1);
                    pb["zfcs"] = query.ReadOne<int>();

                    pb["zfwz7"] = query.ReadOne<int>();
                    var t2 = query.ReadOne<supermodel>();
                    pb["wzyd7"] = t2.Value<int>(0); pb["ggdj7"] = t2.Value<int>(1);
                    pb["zfcs7"] = query.ReadOne<int>();

                    pb["arts"] = query.Read<supermodel>().ToArray();
                };
            });

        }

        public static void s0(pagebase pb)
        {
            s(pb);
        }
        public static void s00(pagebase pb)
        {
            s(pb);
        }
        /// <summary>
        /// 显示文章，分享文章
        /// </summary>
        /// <param name="pb"></param>
        public static void s(pagebase pb)
        {
            if (defaultcontroller.TEST)
            {
                pb["lxw_edit"] = "1";
                pb["jiami"] = "1";
            }
            //判断用户openid
            var openid = cookieshelper.getcookie("openidx");
            var code = pb.v_ss("u");
            var newopenid = pb.v_ss("id");

            _Articles art = queryhelper.get<_Articles>("select * from Articles where code=@0", code);


            if (art.openid == "admin")
            {
                //更新
                queryhelper.execute("update Articles set openid=@1 where code=@0", code, openid);
                art.openid = openid;
            }

            if (art.openid == "xuqianqian")
            {
                //更新
                queryhelper.execute("update Articles set openid=@1 where code=@0", code, openid);
                art.openid = openid;

                //判断是否有广告，然后插入广告
                var count = queryhelper.get<int>("select count(1) from ztbad where openid=@0", art.openid);
                if (count == 0)
                {
                    saveADS("jzyh", "http://mp.weixin.qq.com/s?__biz=MzAwNjM4Njc0MA==&mid=400211152&idx=1&sn=056ad0a1f63f8852a41427c45ebb8244&scene=1&srcid=1104FIKyA3cVuIytHXa6vV9p#wechat_redirect", openid);
                }
            }

            if (art.openid == openid)
            {
                pb["lxw_edit"] = "1";
            }
            else
            {
                //阅读次数增加
                queryhelper.execute("update Articles set ReadCount=ReadCount+1 where code=@0", code);
            }

            //输出10条记录
            var arts = queryhelper.query<_Articles>("select top 10 * from Articles where code<>@0 and openid=@1 order by ReadCount desc", code, art.openid);

            dataloger.info("select top 3 * from ztbad where openid=@0 order by xuhao asc:" + art.openid);
            var ads = queryhelper.query<_ZTBAD>("select top 3 * from ztbad where openid=@0 order by xuhao asc", art.openid);

            pb["arts"] = arts;
            pb["ads"] = ads;

            if (art.ArticleID == "WAIBU")
            {
                //除微信外的其他形式
                pb.randerview("s1");
            }
            else
            { 
                using (StreamReader sr = new StreamReader(art.URL))
                {
                    pb["body"] = sr.ReadToEnd();
                }
            }


            var wx = weixincontroller.GZH.JSSDK_FX();
            
            string fcode = "";

            int number = 10000;
             //记录朋友关系
            if (newopenid != "" )
            {
                if (openid != art.openid)
                {
                    try
                    {
                        var fromopenid = queryhelper.get<string>("select openid from yonghu where yonghuid=@0", hs.Decode(newopenid)[0] - number);
                        var yonghuid = queryhelper.get<int>("select yonghuid from yonghu where openid=@0", openid);
                        fcode = "&id=" + hs.Encode(yonghuid + number);

                        _guanxi guanxi = new _guanxi();


                        var Request = pb.Request;
                        //获取URL地址
                        guanxi.url = Request.Url.ToString();
                        //获取IP地址
                        guanxi.ips = requesthelper.clientip();

                        //浏览器
                        guanxi.fr = Request.Browser.Platform;//.ToString();
                        guanxi.cp = Request.UserAgent.ToString();
                        //操作系统
                        guanxi.UserAgent = Agent(Request.UserAgent.ToString());
                        //浏览器版本号
                        //guanxi.ClrVersion = Request.Browser.ClrVersion.ToString();
                        guanxi.http_referer = Request.ServerVariables["http_referer"];

                        guanxi.wxfrom = wx.from;
                        guanxi.isappinstalled = wx.isappinstalled;

                        guanxi.fromopenid = fromopenid;
                        guanxi.toopenid = openid;
                        guanxi.code = code;
                        guanxi.tianjiariqi = DateTime.Now;
                        if (guanxi.ips != "" && guanxi.ips != "127.0.0.1")
                            guanxi.city = WeiXin_Map.GetCity(guanxi.ips);

                        guanxi.saveorupdate();
                    }
                    catch (Exception err)
                    {
                        dataloger.fatal("newopenid", err);
                    }
                }
            }
            else
            {
                if (openid == art.openid)
                {
                    var yonghuid = queryhelper.get<int>("select yonghuid from yonghu where openid=@0", openid);
                    fcode = "&id=" + hs.Encode(yonghuid + number);
                }
            }

            //微信朋友圈分析处理
            pb["art"] = art;
            art.Title = stringhelper.htmldecode(art.Title);
            pb["img"] = "http://" + weixincontroller.domain + art.ImageUrl.Replace("\\", "/");
            pb["purl"] = "http://" + weixincontroller.domain + "/s?u=" + code + fcode;
            pb["domain"] = weixincontroller.domain;

            //输出js签名
        }

        private static void saveADS(string p1, string p2,string openid)
        {
            string sql = @"
            insert into ZTBAD(xuhao,url,link,openid)
values
(1,'/adimages/[p1]_1.jpg','[p2]','[openid]')
insert into ZTBAD(xuhao,url,link,openid)
values
(2,'/adimages/[p1]_2.jpg','[p2]','[openid]')
insert into ZTBAD(xuhao,url,link,openid)
values
(3,'/adimages/[p1]_3.jpg','[p2]','[openid]')";
            sql = sql.Replace("[p1]", p1);
            sql = sql.Replace("[p2]", p2);
            sql = sql.Replace("[openid]", openid);

            queryhelper.execute(sql);
        }
        static Hashids hs = new Hashids("this is my yonghuid");

        static string Agent(string agent)
        {

            string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };

            //排除 Windows 桌面系统
            if (!agent.Contains("Windows NT") || (agent.Contains("Windows NT") && agent.Contains("compatible; MSIE 9.0;")))
            {
                //排除 苹果桌面系统
                if (!agent.Contains("Windows NT") && !agent.Contains("Macintosh"))
                {
                    foreach (string item in keywords)
                    {
                        if (agent.Contains(item))
                        {
                            return item;
                        }
                    }
                }
            }

            return "";
        }

    }
}
